package com.example.demo.controller;

import com.example.demo.config.UploadProperties;
import com.example.demo.dto.ChatMessageDTO;
import com.example.demo.dto.CustomerServiceConnection;
import com.example.demo.dto.ResponseResult;
import com.example.demo.entity.ChatMessage;
import com.example.demo.service.ChatMessageService;
import com.example.demo.service.impl.UserServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/app/chat")
public class ChatController {

    private final SimpMessagingTemplate messagingTemplate;
    private final ChatMessageService chatMessageService;
    private final UserServiceImpl userServiceImpl;
    private final UploadProperties uploadProperties;

    @Autowired
    public ChatController(SimpMessagingTemplate messagingTemplate, ChatMessageService chatMessageService, UserServiceImpl userServiceImpl,UploadProperties uploadProperties) {
        this.messagingTemplate = messagingTemplate;
        this.chatMessageService = chatMessageService;
        this.userServiceImpl = userServiceImpl;
        this.uploadProperties = uploadProperties;
    }

    // 接收用户消息
    @MessageMapping("/user/send") // App发送到/app/user/send
    public void handleUserMessage(ChatMessage message) {
        // 1. 保存到数据库
        System.out.println(message);
        message.setTimeStamp(LocalDateTime.now());
        chatMessageService.addChatMessage(message);

        // 2. 推送消息给对应客服
        CustomerServiceConnection agent = userServiceImpl.getCustomerServiceConnection(message.getUserId());
        messagingTemplate.convertAndSend("/topic/agent/" + agent.getAgentId(), message); // 只推送给该客服

        // 推送消息给用户自己
        messagingTemplate.convertAndSend("/topic/user/" + message.getUserId(), message);

//        System.out.println("收到消息: " + message.getContent() + ", 来自用户: " + message.getUserId());
    }

    // 在Controller中添加模拟回复
    @GetMapping("/get/mock-reply")
    public String mockAgentReply(@RequestParam String userId,
                                 @RequestParam String text) {
        messagingTemplate.convertAndSend(
                "/topic/user/" + userId,
                new ChatMessage("agent", text)
        );
        return "已发送模拟回复";
    }

    @GetMapping("/get/history")
    public ResponseResult<List<ChatMessageDTO>> getHistory(@RequestParam String userId) {
        List<ChatMessageDTO> allMessageByUserId;
        try {
            allMessageByUserId = chatMessageService.getAllMessageByUserId(userId);
        } catch (Exception e) {
            return new ResponseResult<>(200, e.getMessage(), Collections.emptyList());
        }
        return new ResponseResult<>(200, "查询成功！", allMessageByUserId);
    }

    @PostMapping("/post/uploadFile")
    public ResponseResult<String> uploadFile(@RequestParam("file") MultipartFile file) {
        System.out.println(file.getOriginalFilename());
        if (file.isEmpty()) {
            return new ResponseResult<>(500,"上传的文件为空");
        }
        try {
            // 判断文件类型
            String contentType = file.getContentType();
            String fileType = "other";
            if (contentType != null) {
                if (contentType.startsWith("image/")) {
                    fileType = "image";
                } else if (contentType.startsWith("audio/")) {
                    fileType = "audio";
                }
            }
            // 生成文件名
            String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
            String saveDir = uploadProperties.getBaseDir() + fileType + "/";
            File dir = new File(saveDir);
            if (!dir.exists()) dir.mkdirs();
            String savePath = saveDir + fileName;
            file.transferTo(new File(savePath));

            // 返回可访问URL
            String url = "/" + fileType + "/" + fileName;
            return new ResponseResult<>(200,"响应成功！",url);
        } catch (Exception e) {
            return new ResponseResult<>(500,"上传失败" + e.getMessage());
        }
    }
}
